import { isString } from './type';

export const trim = (str: string | null | undefined, charsToTrim = ' ') => {
    if (!str) return '';
    const toTrim = charsToTrim.replace(/[\W]{1}/g, '\\$&');
    const regex = new RegExp(`^[${toTrim}]+|[${toTrim}]+$`, 'g');
    return str.replace(regex, '');
};

export const decodeString = function (value: string, defaultVal?: string) {
    try {
        if (isString(value)) {
            return decodeURIComponent(value);
        }
    } catch (error) {
        console.log(`${value}解码错误`);
        return defaultVal || '';
    }
};

export const encodeString = function (val: any) {
    if (val) {
        if (val instanceof Object) {
            return encodeURIComponent(JSON.stringify(val));
        }
        return encodeURIComponent(trim(val));
    }
    return '';
};
export const objToQueryStr = (obj: Record<string, any>) => {
    return Object.entries(obj)
        .map(([k, v]) => `${k}=${v}`)
        .join('&');
};

export const parseUrlParams = function (path: string) {
    if (!path || !isString(path)) {
        return {};
    }
    const params: Record<string, any> = {};
    const paramPairs = path.split('&');
    for (const pair of paramPairs) {
        const [key, value] = pair.split('=');
        const decodedValue = decodeString(value);
        params[key] = decodedValue;
    }
    return params;
};
